package com.qili.controller.supervisor;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.annotation.Guide;
import com.qili.base.controller.BaseController;
import com.qili.base.entity.CurrentUser;
import com.qili.core.annotation.Log;
import com.qili.core.shiro.Principal;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.core.utils.FileUtils;
import com.qili.entity.affaircase.dto.AffairCaseDTO;
import com.qili.entity.base.*;
import com.qili.entity.jc.dto.JcProjectDTO;
import com.qili.entity.supervisor.*;
import com.qili.entity.supervisor.dto.*;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.dto.ProjectPlaceDTO;
import com.qili.entity.supplier.dto.SupplierProjectDTO;
import com.qili.entity.sys.SysLog;
import com.qili.entity.sys.SysRegion;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.entity.zx.ExProjectBigEvent;
import com.qili.entity.zx.ZxProject;
import com.qili.exception.MyException;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.affairCase.AffairCaseService;
import com.qili.service.base.*;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.sys.SysRegionService;
import com.qili.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipOutputStream;

import static java.util.Objects.isNull;

@Controller
@Slf4j
@RequestMapping("/project/projectManager")
public class ProjectController extends BaseController {


    @Autowired
    SysUserService sysUserService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    SysUserService userService;


    @Autowired
    AffairCaseService affairCaseService;


    @Autowired
    SupervisorFileService supervisorFileService;

    @Autowired
    TmbFileService tmbFileService;

    @Value("${supervisor.downloadPath}")
    private String uploadPath;
    @Value("${supervisor.tempPath}")
    private String tempPath;

    @Value("${supervisor.fileMbPath}")
    private String fileMbPath;


    @Autowired
    SysLogMapper sysLogMapper;


    @Autowired
    private SupervisorProjectService supervisorProjectService;


    @Autowired
    private ProjectUnitConstructionService projectUnitConstructionService;

    /**
     * 监理标准规范
     *
     * @return
     */
    @GetMapping(value = "/index")
    public String index(Model model, HttpServletRequest request) {
        CurrentUser currentUser = CommonUtil.getUser();
        String userId = CommonUtil.getUserId();
        SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
        if (sysUser == null) {
            // 跳转到登陆页面
            request.setAttribute("type", "login");
            return "/login";
        }
        // 个人中心设置的数量
        String tagnum = sysUser.getNumTag();
        currentUser.setNumTag(tagnum);
        String AsTags = currentUser.getTags();
        String[] AyTags;

        // 2021 0820 已经删除的项目 不能在显示
        Session session = Principal.getSession();
        session.setAttribute("currentPrincipal", currentUser);
        SupervisorFile supervisorFile = supervisorFileService.getPersonalImg(userId);
        request.setAttribute("file", supervisorFile);
        String menutype = request.getParameter("type");
        model.addAttribute("menutype", menutype);
        return "/project/index/index";
    }

    /**
     * @param model
     * @param request
     * @Author:zhaoyongke
     * @Description:监理
     * @Date: 2024/11/2 10:59
     */
    @GetMapping("/jlbzgf/index")
    public String managerIndex(Model model, HttpServletRequest request) {
        model.addAttribute("type", "1");
        return "/project/jlbzgf/index";
    }

    /**
     * @param model
     * @param request
     * @Author:zhaoyongke
     * @Description:承建模版
     * @Date: 2024/11/2 10:59
     */
    @GetMapping("/cjbzgf/index")
    public String cjbzgfIndex(Model model, HttpServletRequest request) {
        model.addAttribute("type", "2");
        return "/project/jlbzgf/index";
    }

    @ApiOperation(value = "/showFileList", httpMethod = "GET", notes = "展示项目")
    @GetMapping(value = "showFileList")
    @ResponseBody
    public ReType showFileList(TbmFileDTO tmbFile, Model model, String page, String limit) {
        ReType result = tmbFileService.show(tmbFile, Integer.valueOf(page), Integer.valueOf(limit));
        return result;
    }

    /**
     * 项目管理----放到回收站
     **/
    @ApiOperation(value = "/jlbzgf/deleteFile", httpMethod = "POST", notes = "放入回收站项目")
    @Log(desc = "删除文件", type = Log.LOG_TYPE.DEL)
    @PostMapping(value = "/jlbzgf/deleteFile")
    @ResponseBody
    public JsonUtil deleteHs(@RequestParam String ids) {
        if (StringUtils.isEmpty(ids)) {
            return JsonUtil.error("获取数据失败");
        }
        JsonUtil re = new JsonUtil();
        try {
            List<String> list = Tutil.split(ids);
            for (int i = 0; i < list.size(); i++) {
                tmbFileService.deleteByPrimaryKey(list.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
            re.setMsg("操作失败");
            re.setFlag(false);
        }
//        tmbFileService.deleteByPrimaryKey(ids);
        re.setFlag(true);
        re.setMsg("操作成功");
        return re;
    }





    @RequestMapping(value = "/jlbzgf/addFile", method = RequestMethod.POST)
    @ResponseBody
    public JsonUtil File(@RequestParam(value = "file", required = false) MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        JsonUtil re = new JsonUtil();
        String type = request.getParameter("type");//文件类型
        String realPath = fileMbPath;
        String format = DateUtil.getCurrentDateNoSpliter();
        String path = realPath + format;
        File folder = new File(path);
        //判断文件是否存在
        if (!folder.exists()) {//不存在，则创建
            //这里需要使用mkdirs，因为为多层目录
            folder.mkdirs();
        }
        String oldName = multipartFile.getOriginalFilename();
        boolean validFilename = FileUtils.isValidFilename(oldName);
        if (!validFilename) {
            re.setFlag(false);
            re.setMsg("文件名称不合法");
            return re;
        }
        String newName = IdUtil.simpleUUID().toString() + oldName;
        //文件保存
        multipartFile.transferTo(new File(folder, newName));
        TmbFile tmbFile = new TmbFile();
        tmbFile.setType(type);
        tmbFile.setFileName(oldName);
        tmbFile.setUrl(path + File.separator + newName);
        tmbFile.setCreateBy(CommonUtil.getUser().getId());
        tmbFile.setCreateDate(new Date());
        tmbFile.setFileType(FileUtil.getSuffix(newName));
        tmbFileService.insert(tmbFile);
        re.setFlag(true);
        re.setMsg("操作成功");
        return re;


    }

    /**
     * @param request
     * @param response
     * @Author:zhaoyongke
     * @Description:导出
     * @Date: 2024/11/3 9:54
     */
    @GetMapping(value = "/jlbzgf/export")
    public void export(@RequestParam String id, HttpServletRequest request, HttpServletResponse response) {
        // 获取选择的文件
        TmbFile tmbFile = tmbFileService.selectByPrimaryKey(id);
        String fileName = tmbFile.getFileName();
        ExportFileUtil.exportFileNew(response, request, tmbFile.getUrl(), fileName);
    }

    @GetMapping(value = "/projectFile/export")
    public void exportProjectFile(@RequestParam String id, HttpServletRequest request, HttpServletResponse response) {
        SupervisorFile supervisorFile = supervisorFileService.selectByPrimaryKey(id);
        ExportFileUtil.exportFileNew(response, request, supervisorFile.getUrl(), "");
    }

    /**
     * 项目文件---删除
     **/
    @PostMapping(value = "/project/deleteFile")
    @ResponseBody
    public JsonUtil projectDeleteFile(@RequestParam String ids) {
        if (StringUtils.isEmpty(ids)) {
            return JsonUtil.error("获取数据失败");
        }
        JsonUtil re = new JsonUtil();
        try {
            List<String> list = Tutil.split(ids);
            for (int i = 0; i < list.size(); i++) {
                supervisorFileService.deleteByPrimaryKey(list.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
            re.setMsg("操作失败");
            re.setFlag(false);
        }
        re.setFlag(true);
        re.setMsg("操作成功");
        return re;
    }

    /**
     * @param model
     * @param request
     * @Author:zhaoyongke
     * @Description:显示上传组件
     * @Date: 2024/11/3 9:55
     */
    @GetMapping(value = "/jlbzgf/showUpload")
    public String showUpload(Model model, HttpServletRequest request) {
        String type = request.getParameter("type");
        System.out.println(type);
        model.addAttribute("type", type);// 文件类型
        return "/project/jlbzgf/uploadFile";
    }

    @Autowired
    ProjectContractService projectContractService;


    /**
     * @param model
     * @param request
     * @Author:zhaoyongke
     * @Description:项目文件集
     * @Date: 2024/11/2 10:59
     */
    @GetMapping("/projectFile/index")
    public String projectFile(Model model, HttpServletRequest request) {
        SupervisorProjectDTO projectDTO = new SupervisorProjectDTO();
        List<SupervisorProjectDTO> supervisorProjectDTOS = supervisorProjectService.selectSupervisorProjectOrder(projectDTO);
        String projectId = "";
        if (!CollectionUtil.isEmpty(supervisorProjectDTOS)) {
            projectId = supervisorProjectDTOS.get(0).getId();
        } else {
            projectId = "454545";
        }
        model.addAttribute("projectId", projectId);
        //查询本项目的分包
        ProjectContractDTO projectContract = new ProjectContractDTO();
        projectContract.setProjectId(projectId);
        List<ProjectContract> listfb = projectContractService.selectPackge(projectContract);
        request.setAttribute("listfb", listfb);// 项目分包if

        Subject subject = SecurityUtils.getSubject();
        // 判断是否是项目经理角色
        if (subject.hasRole("xmjl")){
            request.setAttribute("isxmjl", "1");
        }else{
            request.setAttribute("isxmjl", "0");
        }
        return "/project/projectFile/index";
    }


    /**
     * @Author:zhaoyongke
     * @Description:项目文件查询
     * @Date: 2024/11/3 10:06
     */
    @GetMapping(value = "showProjectFileList")
    @ResponseBody
    public ReType showProjectFileList(SupervisorFile file, Model model, String page, String limit) {
        ReType result = supervisorFileService.show(file, Integer.valueOf(page), Integer.valueOf(limit));
        return result;
    }

    /**
     * @param model
     * @param request
     * @Author:zhaoyongke
     * @Description:项目进度
     * @Date: 2024/11/3 12:42
     */
    @GetMapping("/projectJd/index")
    public String projectJd(Model model, HttpServletRequest request) {
        SupervisorProjectDTO projectinfo = this.getProjectInfo();
        model.addAttribute("projectInfo", projectinfo);
        String projectId = StringUtil.isBlank(projectinfo.getId()) ? "454545" : projectinfo.getId();
        //查询本项目的分包
        ProjectContractDTO projectContract = new ProjectContractDTO();
        projectContract.setProjectId(projectId);
        List<ProjectContract> listfb = projectContractService.selectPackge(projectContract);
        model.addAttribute("listfb", listfb);// 项目分包if
        model.addAttribute("projectId", projectinfo.getProjectId());
        model.addAttribute("fbnum", listfb.size());// 项目分包数量
        return "/project/projectJd/index";
    }

    @Autowired
    TjdStageService tjdStageService;

    /**
     * @param dto
     * @param model
     * @param page
     * @param limit
     * @Author:zhaoyongke
     * @Description:进度查询
     * @Date: 2024/11/3 16:23
     */
    @GetMapping(value = "/projectJd/showJdStageList")
    @ResponseBody
    public ReType showJdStageList(TjdStageDTO dto, Model model, String page, String limit) {
        if ("2".equals(dto.getType()) && StringUtil.isBlank(dto.getParentId())) {
            // 查询里程（处理一开始里程信息所有显示的问题）
            dto.setParentId("232323233");
        }
        // 1 总体   2 分包  // 如果是总体  查询的是分包Id 为空的阶段
        String xmType = dto.getXmType();


        ReType result = tjdStageService.show(dto, Integer.valueOf(page), Integer.valueOf(limit));
        return result;
    }

    @GetMapping(value = "/projectJd/showNoJdStageList")
    @ResponseBody
    public ReType showNoJdStageList(TjdStageDTO dto, Model model) {
        if ("2".equals(dto.getType()) && StringUtil.isBlank(dto.getParentId())) {
            // 查询里程（处理一开始里程信息所有显示的问题）
            dto.setParentId("232323233");
        }
        // 1 总体   2 分包  // 如果是总体  查询的是分包Id 为空的阶段
        String xmType = dto.getXmType();
        ReType result = tjdStageService.show(dto, Integer.valueOf(1), Integer.valueOf(1000));
        return result;
    }


    /**
     * @Author:zhaoyongke
     * @Description:添加
     * @Date: 2024/11/3 16:29
     */
    @GetMapping(value = "/projectJd/addJdStagePage")
    public String addJdStagePage(Model model, HttpServletRequest request) {

        String fbId = request.getParameter("fbId");//分包Id
        String projectId = request.getParameter("projectId");//项目Id
        String parentId = request.getParameter("parentId");//parentId
        model.addAttribute("fbId", fbId);//
        model.addAttribute("projectId", projectId);//
        model.addAttribute("parentId", parentId);//
        TjdStageDTO parentStage = new TjdStageDTO();
        if (!StringUtil.isBlank(parentId)) {
            parentStage = tjdStageService.selectStageById(parentId);
            model.addAttribute("parentStage", parentStage);//里程
            model.addAttribute("type", "2");//
        } else {
            // 阶段
            model.addAttribute("type", "1");//
            model.addAttribute("parentStage", parentStage);//里程
        }
        return "/project/projectJd/add_stage";
    }

    /**
     * @Author:zhaoyongke
     * @Description:查看项目进度
     * @Date: 2024/11/3 16:29
     */
    @GetMapping(value = "/projectJd/viewstageprocess")
    public String viewstageprocess(Model model, HttpServletRequest request) {
        //项目Id
        String projectId = request.getParameter("projectId");
        // 分包Id
        String fbId = request.getParameter("fbId");//、
        // 总体或分包
        String xmType = StringUtil.isBlank(fbId) ? "1" : "2";
        model.addAttribute("projectId", projectId);
        model.addAttribute("fbId", fbId);
        //  1 总体   2 分包
        model.addAttribute("xmType", xmType);
        // 1 阶段  2 里程
        model.addAttribute("type", "1");
        //
        return "/project/projectJd/process";
    }

    /**
    * @Author:zhaoyongke
    * @Description: 首页项目进度显示----总项目进度
    * @param model
    * @param request
    * @Date: 2024/12/5 11:41
    */
    @ResponseBody
    @RequestMapping("/projectJdIndex/tableHead")
    public JsonUtil projectJdIndexTableHead(Model model, HttpServletRequest request) {

        JsonUtil result = new JsonUtil();
        SupervisorProjectDTO projectinfo = this.getProjectInfo();
        String projectId = StringUtil.isBlank(projectinfo.getId()) ? "454545" : projectinfo.getId();
        TjdStageDTO  tjdStageDTO=new TjdStageDTO();
        // 查询阶段
        tjdStageDTO.setType("1");
        // 查询总进度
        tjdStageDTO.setXmType("1");
        tjdStageDTO.setProjectId(projectId);
        List<TjdStageDTO> tjdStageDTOS = tjdStageService.selectMaxAndMinDate(tjdStageDTO);
        String startDateStr="";
        String endDateStr="";
        if(CollectionUtil.isNotEmpty(tjdStageDTOS)){
            // 最早的开始和结束时间
            startDateStr = tjdStageDTOS.get(0).getStartDateStr();
            endDateStr = tjdStageDTOS.get(0).getEndDateStr();
        }
        List<ColNew> colList = this.getFormStatisticstableHead("",startDateStr,endDateStr);
        HashMap<String, Object> map = new HashMap<>();
        map.put("colList", colList);
        map.put("projectId", projectId);
        result.setFlag(true);
        result.setData(map);
        return result;
    }

    @ResponseBody
    @RequestMapping("/projectJd/tableHead")
    public JsonUtil getFormStatisticstableHead(Model model, HttpServletRequest request) {
        JsonUtil result = new JsonUtil();

        String fbId = request.getParameter("fbId");//分包Id
        String projectId = request.getParameter("projectId");//项目Id
        TjdStageDTO  tjdStageDTO=new TjdStageDTO();
        tjdStageDTO.setType("1");
        if(StringUtils.isEmpty(fbId)){
            // 查询总进度
            tjdStageDTO.setXmType("1");
        }else{
            tjdStageDTO.setFbId(fbId);
        }
        tjdStageDTO.setProjectId(projectId);
        List<TjdStageDTO> tjdStageDTOS = tjdStageService.selectMaxAndMinDate(tjdStageDTO);
        String startDateStr="";
        String endDateStr="";
        if(CollectionUtil.isNotEmpty(tjdStageDTOS)){
            // 最早的开始和结束时间
             startDateStr = tjdStageDTOS.get(0).getStartDateStr();
             endDateStr = tjdStageDTOS.get(0).getEndDateStr();
        }
        List<ColNew> colList = this.getFormStatisticstableHead(fbId,startDateStr,endDateStr);
        result.setFlag(true);
        result.setData(colList);
        return result;
    }

    public List<ColNew> getFormStatisticstableHead(String fbId,String startDateStr,String endDateStr) {
        // 根据startDateStr 和 endDateStr 遍历每一个月份 比如 startDateStr  202405  endDateStr 202409
        List<ColNew> colArrayList = new ArrayList<>();
//        colArrayList.add(new ColNew("orderNum", "序号", "100", null, null, null, false,"left"));
        if(StringUtils.isEmpty(fbId)){
            colArrayList.add(new ColNew("stageName", "标段名称", "150", null, null, null, false,"left"));
        }else{
            colArrayList.add(new ColNew("stageName", "阶段名称", "150", null, null, null, false,"left"));
        }

        colArrayList.add(new ColNew("startDateStr", "开始时间", "180", null, null, null, false,""));
        colArrayList.add(new ColNew("endDateStr", "结束时间", "180", null, null, null, false,""));
        colArrayList.add(new ColNew("status", "状态", "100","#status" , null, null, false,""));
        List<String> dateRange = generateDateRange(startDateStr, endDateStr);

        String  width="15%";
        if(dateRange.size()==1){
            width="54%";
        }else if(dateRange.size()==2){
            width="30%";
        }
        for (int i = 0; i < dateRange.size(); i++) {
            String dateStr = dateRange.get(i);
            colArrayList.add(new ColNew("dateStr"+i, dateStr, width, "#datestr", null, null, false,""));
        }

        return colArrayList;
    }

       public static List<String> generateDateRange(String startDateStr, String endDateStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        LocalDate startDate = LocalDate.parse(startDateStr + "01", DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate endDate = LocalDate.parse(endDateStr + "01", DateTimeFormatter.ofPattern("yyyyMMdd"));

        List<String> dateRange = new ArrayList<>();
        LocalDate currentDate = startDate;

        while (!currentDate.isAfter(endDate)) {
            dateRange.add(currentDate.format(formatter));
            currentDate = currentDate.plusMonths(1);
        }

        return dateRange;
    }


    @GetMapping(value = "/projectJd/updateJdStagePage")
    public String updateJdStagePage(Model model, HttpServletRequest request) {
        String id = request.getParameter("id");//、
        TjdStageDTO tjdStage = tjdStageService.selectStageById(id);
        if (tjdStage != null) {
            String parentId = tjdStage.getParentId();
            TjdStageDTO parentStage = new TjdStageDTO();
            if (!StringUtil.isBlank(parentId)) {
                parentStage = tjdStageService.selectStageById(parentId);
                model.addAttribute("parentStage", parentStage);//里程
                model.addAttribute("type", "2");//
            } else {
                // 阶段
                model.addAttribute("type", "1");//
                model.addAttribute("parentStage", parentStage);//里程
            }
            System.out.println("进入编辑页面的===================================");
            model.addAttribute("stagedto", tjdStage);
        }

        return "/project/projectJd/update_stage";
    }


    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:添加
     * @Date: 2024/11/3 16:29
     */
    @PostMapping(value = "/projectJd/addJdStage")
    @ResponseBody
    public JsonUtil addJdStage(TjdStageDTO dto) {
        JsonUtil jsonUtil = new JsonUtil();
        TjdStage tjdStage = new TjdStage();
        tjdStage.setStartDate(DateUtil.parseDate(dto.getStartDateStr(), "yyyy-MM-dd"));
        tjdStage.setEndDate(DateUtil.parseDate(dto.getEndDateStr(), "yyyy-MM-dd"));
        tjdStage.setProjectId(dto.getProjectId());
        tjdStage.setOrderNum(dto.getOrderNum());
        tjdStage.setFbId(dto.getFbId());
        tjdStage.setStageName(dto.getStageName());
        tjdStage.setParentId(dto.getParentId());
        tjdStageService.insert(tjdStage);
        jsonUtil.setFlag(true);
        jsonUtil.setMsg("创建成功");
        return jsonUtil;
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:修改
     * @Date: 2024/11/3 16:29
     */

    @PostMapping(value = "/projectJd/updateJdStage")
    @ResponseBody
    public JsonUtil updateJdStage(TjdStageDTO dto) {
        JsonUtil jsonUtil = new JsonUtil();
        String id = dto.getId();
        TjdStage tjdStage = tjdStageService.selectByPrimaryKey(id);
        tjdStage.setStartDate(DateUtil.parseDate(dto.getStartDateStr(), "yyyy-MM-dd"));
        tjdStage.setEndDate(DateUtil.parseDate(dto.getEndDateStr(), "yyyy-MM-dd"));
//        tjdStage.setProjectId(dto.getProjectId());
        tjdStage.setOrderNum(dto.getOrderNum());
//        tjdStage.setFbId(dto.getFbId());
        tjdStage.setStageName(dto.getStageName());
        tjdStageService.updateByPrimaryKey(tjdStage);
        jsonUtil.setFlag(true);
        jsonUtil.setMsg("修改成功");
        return jsonUtil;
    }



    /**
     * @Author:zhaoyongke
     * @Description:删除
     * @Date: 2024/11/3 16:29
     */
    @PostMapping(value = "/projectJd/deleteJb")
    @ResponseBody
    public JsonUtil deleteJb(@RequestParam String ids) {
        if (StringUtils.isEmpty(ids)) {
            return JsonUtil.error("获取数据失败");
        }
        TjdStage tjdStage = tjdStageService.selectByPrimaryKey(ids);
        String parentId = tjdStage.getParentId();

        TjdStage chidlStage = new TjdStage();
        chidlStage.setParentId(tjdStage.getId());
        List<TjdStage> chidlStageList = tjdStageService.select(chidlStage);
        for (int i = 0; i < chidlStageList.size(); i++) {
            tjdStageService.deleteByPrimaryKey(chidlStageList.get(i).getId());
        }

        JsonUtil re = new JsonUtil();
        tjdStageService.deleteByPrimaryKey(ids);
        re.setFlag(true);
        re.setMsg("操作成功");
        return re;
    }

       public static void main(String[] args) {
        String startDateStr = "202405";
        String endDateStr = "202509";

        List<String> dateRange = generateDateRange(startDateStr, endDateStr);
        for (String date : dateRange) {
            System.out.println(date);
        }
    }


    @Autowired
    NoticeNewServie  noticeNewServie;
    /**
    * @Author:zhaoyongke
    * @Description: 消息列表
    * @param dto
    * @param page
    * @param limit
    * @Date: 2024/12/2 14:04
    */
    @GetMapping(value = "queryNoticeList")
    @ResponseBody
    public ReType queryNoticeList(NoticeNewDTO dto, String page, String limit) {
        Subject subject = SecurityUtils.getSubject();
        // 项目经理角色 业主单位项目负责人   业主单位管理员
        if (subject.hasRole("xmjl") || subject.hasRole("jsdwxmfzr") || subject.hasRole("jsdwglry")) {
            // 查询全部
            System.out.println("项目经理角色========================");
        }
        // nupm 承建单位项目经理
        if (subject.hasRole("nupm")) {
            // 查询本自己的
            System.out.println("承建单位角色========================");
            dto.setReceivePerson(CommonUtil.getUserId());
        }
        ReType re = noticeNewServie.queryNoticeList(dto, Integer.valueOf(page), Integer.valueOf(limit));
        return re;
    }



    @GetMapping("/projectNotice/index")
    public String projectNotice(Model model, HttpServletRequest request) {

        SupervisorProjectDTO projectinfo = this.getProjectInfo();

        model.addAttribute("projectInfo", projectinfo);
        String projectId = StringUtil.isBlank(projectinfo.getId()) ? "454545" : projectinfo.getId();
        //查询本项目的分包
        ProjectContractDTO projectContract = new ProjectContractDTO();
        projectContract.setProjectId(projectId);
        List<ProjectContract> listfb = projectContractService.selectPackge(projectContract);
        model.addAttribute("listfb", listfb);// 项目分包if
        model.addAttribute("projectId", projectinfo.getProjectId());
        model.addAttribute("fbnum", listfb.size());// 项目分包数量
        // 城建单位表
        ProjectUnitConstructionDTO projectUnitConstruction = new ProjectUnitConstructionDTO();
        projectUnitConstruction.setSupervisorProjectId(projectId);
        List<ProjectUnitConstructionDTO> listcj = projectUnitConstructionService.selectProjectUnitList(projectUnitConstruction);
        model.addAttribute("listcj", listcj);// 项目分包数量
        return "/project/notice/index";
    }


    public   SupervisorProjectDTO getProjectInfo(){
        SupervisorProjectDTO projectDTO = new SupervisorProjectDTO();
        List<SupervisorProjectDTO> supervisorProjectDTOS = supervisorProjectService.selectSupervisorProjectOrder(projectDTO);
        SupervisorProjectDTO projectinfo = null;
        if (!CollectionUtil.isEmpty(supervisorProjectDTOS)) {
            projectinfo = supervisorProjectDTOS.get(0);
        } else {
            projectinfo = new SupervisorProjectDTO();
        }
        return   projectinfo;
    }
    /**
     * 项目消息---删除消息
     **/
    @PostMapping(value = "/notice/deleteNotice")
    @ResponseBody
    public JsonUtil deleteNotice(@RequestParam String ids) {
        if (StringUtils.isEmpty(ids)) {
            return JsonUtil.error("获取数据失败");
        }
        JsonUtil re = new JsonUtil();
        try {
            List<String> list = Tutil.split(ids);
            for (int i = 0; i < list.size(); i++) {
                noticeNewServie.deleteByPrimaryKey(list.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
            re.setMsg("操作失败");
            re.setFlag(false);
        }
        re.setFlag(true);
        re.setMsg("操作成功");
        return re;
    }




    /**
     * 项目消息---发送消息
     **/
    @GetMapping("/projectNotice/sendNoticePage")
    public String sendNoticePage(Model model, HttpServletRequest request) {
        SupervisorProjectDTO projectinfo = this.getProjectInfo();
        model.addAttribute("projectInfo", projectinfo);
        String projectId = StringUtil.isBlank(projectinfo.getId()) ? "454545" : projectinfo.getId();
        //查询本项目的分包
        ProjectContractDTO projectContract = new ProjectContractDTO();
        projectContract.setProjectId(projectId);
        List<ProjectContract> listfb = projectContractService.selectPackge(projectContract);
        model.addAttribute("listfb", listfb);// 项目分包if
        model.addAttribute("projectId", projectinfo.getProjectId());
        model.addAttribute("fbnum", listfb.size());// 项目分包数量
        // 城建单位表
        ProjectUnitConstructionDTO projectUnitConstruction = new ProjectUnitConstructionDTO();
        projectUnitConstruction.setSupervisorProjectId(projectId);
        List<ProjectUnitConstructionDTO> listcj = projectUnitConstructionService.selectProjectUnitList(projectUnitConstruction);
        model.addAttribute("listcj", listcj);// 项目分包数量
        return "/project/notice/sendindex";
    }


    @ResponseBody
    @GetMapping(value = "/getCjdw")
    public ReType getCjdw() {
        ReType re = new ReType();
        try {
            SupervisorProjectDTO projectinfo = this.getProjectInfo();
            String projectId = StringUtil.isBlank(projectinfo.getId()) ? "454545" : projectinfo.getId();
            // 城建单位表
            ProjectUnitConstructionDTO projectUnitConstruction = new ProjectUnitConstructionDTO();
            projectUnitConstruction.setSupervisorProjectId(projectId);
            List<ProjectUnitConstructionDTO> listcj = projectUnitConstructionService.selectProjectUnitList(projectUnitConstruction);
            re.setCode(200);
            re.setData(listcj);
        } catch (Exception e) {
            e.printStackTrace();
            re.setCode(1);
            re.setMsg("获取用户字典异常！！" + e.getMessage());
        }
        return re;
    }



    @PostMapping(value = "/notice/noticeAdd")
    @ResponseBody
    public JsonUtil noticeAdd(NoticeNewDTO dto) {
        JsonUtil jsonUtil = new JsonUtil();
        // 承建单位
        String selectCj = dto.getSelectCj();
        if(StringUtils.isBlank(selectCj)){
            throw new RuntimeException("请选择承建单位");
        }

        String[] split = selectCj.split(",");
        for (int i = 0; i < split.length; i++) {
            NoticeNew noticeNew = new NoticeNew();
            noticeNew.setContent(dto.getContent());
            noticeNew.setIsView("0");
            noticeNew.setProjectId(dto.getProjectId());
            noticeNew.setSendPerson(CommonUtil.getUserId());
            String s = split[i];
            // 查询项目经理
            ProjectUnitConstruction projectUnitConstruction = projectUnitConstructionService.selectByPrimaryKey(s);
            noticeNew.setReceivePerson(projectUnitConstruction.getProjectManager());
            noticeNew.setUnitId(s);
            noticeNewServie.insert(noticeNew);
        }
        jsonUtil.setFlag(true);
        jsonUtil.setMsg("修改成功");
        return jsonUtil;
    }

   /**
   * @Author:zhaoyongke
   * @Description: 修改状态
   * @param dto
   * @Date: 2024/12/4 15:11
   */
    @PostMapping(value = "/updateNoticeStatus")
    @ResponseBody
    public JsonUtil updateNoticeStatus(NoticeNewDTO dto) {
        JsonUtil jsonUtil = new JsonUtil();
        String id = dto.getNoticeId();
        NoticeNew noticeNew = noticeNewServie.selectByPrimaryKey(id);
        String receivePerson = noticeNew.getReceivePerson();
        String userId = CommonUtil.getUser().getId();
        if(userId.equals(receivePerson)){
            noticeNew.setIsView("1");
            noticeNewServie.updateByPrimaryKey(noticeNew);
        }
        jsonUtil.setFlag(true);
        jsonUtil.setMsg("修改成功");
        return jsonUtil;
    }



}
